package com.ubxtech.cloud.decoder;

import com.alibaba.fastjson2.JSONObject;
import com.ubxtech.core.exception.ErrorCodeCore;
import com.ubxtech.core.exception.RRException;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * 只有下游httpStatus不是200的时候才会捕获
 * @author Victor.Xiao
 * @since 2023-08-22 20:15
 **/
@Component
@Slf4j
public class FeignErrorDecoder implements ErrorDecoder {
    @Override
    public Exception decode(String methodKey, Response response) {
        try {
            String json = Util.toString(response.body().asReader(StandardCharsets.UTF_8));
            log.error("FeignErrorDecoder捕获异常: methodKey:{},body:{}",methodKey,json);
            JSONObject jsonObject = JSONObject.parseObject(json);
            Object data = jsonObject.get("data");
            Integer code = jsonObject.getInteger("code");
            String message = JSONObject.parseObject(json).getString("msg");
            if (code == null) {
                Integer status = jsonObject.getInteger("status");
                if (status != null) {
                    return new RRException(jsonObject.getString("error"), status);
                }
                return new RRException(ErrorCodeCore.BAD_REQUEST);
            }
            return new RRException(message, code, data);
        } catch (Exception e) {
            log.error("FeignErrorDecoder转化异常",e);
        }
        return new RRException(ErrorCodeCore.INTERNAL_SERVER_ERR);
    }
}
